/*
 * Galaxium Messenger
 * 
 * Copyright (C) 2003-2007 Philippe Durand <draekz@gmail.com>
 * Copyright (C) 2007 Ben Motmans <ben.motmans@gmail.com>
 * Copyright (C) 2007 Paul Burton <paulburton89@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Collections.Generic;
using System.Reflection;

using Galaxium.Core;
using Galaxium.Protocol;

using Mono.Addins;
using Anculus.Core;

namespace Galaxium.Protocol
{
	public static class ActivityUtility
	{
		static bool _ready = false;
		static List<MethodInfo> _activityHandlers;
		
		const string _handlerPath = "/Galaxium/Backends/ActivityUtility";
		
		public static bool Ready
		{
			get { return _ready; }
			set { _ready = value; }
		}
		
		public static void Initialize ()
		{
			_activityHandlers = new List<MethodInfo> ();
			
			LoadHandlers ();
			
			AddinManager.ExtensionChanged += OnExtensionChanged;
		}
		
		/// <summary>
		/// Load the activity handlers which will process emitted activities
		/// </summary>
		static void LoadHandlers ()
		{
			lock (_activityHandlers)
			{
				_activityHandlers.Clear ();
				
				foreach (StaticMethodExtension node in AddinUtility.GetExtensionNodes (_handlerPath))
					_activityHandlers.Add (node.CallMethod);
			}
		}
		
		static void OnExtensionChanged (object o, ExtensionEventArgs args)
		{
			if (args.PathChanged (_handlerPath))
				LoadHandlers ();
		}
		
		/// <summary>
		/// Emit the given activity
		/// </summary>
		/// <param name="sender">
		/// The <see cref="System.Object"/> which emitted the activity
		/// </param>
		/// <param name="activity">
		/// The <see cref="IActivity"/>
		/// </param>
		public static void EmitActivity (object sender, IActivity activity)
		{
			if (!_ready)
				return;
			
			lock (_activityHandlers)
			{
				foreach (MethodInfo handler in _activityHandlers)
				{
					try
					{
						handler.Invoke (null, new object[] { sender, activity });
					}
					catch (Exception ex)
					{
						Log.Error (ex, "Error invoking activity handler");
					}
				}
			}
		}
	}
}